package wordstat;

import jxl.read.biff.BiffException;
import obj.Item;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * User: Vladimir
 * Date: 18.10.12 Time: 22:51
 */
public class WordstatChecker {

    public static final int LIMIT = 5;

    public static void main(String[] args) throws BiffException, IOException, InterruptedException {
//        List<Item> items = Item.parseItemsXlsDir("data/extramobi/body/");
//        String category = "корпус";
//        boolean checkModels = false;
        List<Item> items = Item.parseItemsXlsDir("data/extramobi/accum/");
        String brand = "Samsung";
        String category = "аккумулятор";
        boolean checkModels = true;
//        List<Item> items = Item.parseRemontItems("data/extramobi/remont/remont.xls");
//        String brand = "Sony Ericsson";
//        String category = "ремонт";
//        boolean checkModels = false;
        boolean replaceBrand = false;
        int count = 1;
        boolean trimName = false;
        String currBrand = null;
        for (Item item : items) {
            if (!item.brand.equals(brand)) {
                continue;
            }
            String name = item.name.replace("Sony Ericsson", "sony");
            if (currBrand == null || !currBrand.equals(item.brand)) {
                currBrand = item.brand;
                count = 1;
            }
            String phrase;
            if (trimName) {
                String[] fields = name.split(" ");
                name = fields[0] + " " + fields[1];
                phrase = category + " " + name;
            } else {
                if (replaceBrand) {
                    phrase = category + " " + name.replace(item.brand, "");
                } else {
                    phrase = category + " " + name;
                }
            }

            doCheck(count++, item.name, 1, phrase);
            if (checkModels) {
                List<String> models = item.models;
                int modelCount = 1;
                for (String model : models) {
                    String[] fields = model.split(" ");
                    model = fields[0];
                    if (fields.length > 1) {
                        model = model + " " + fields[1];
                    }
                    phrase = category + " " + model;
                    doCheck(modelCount++, item.brand + " " + model, 1, phrase);
                }
            }
        }
    }

    private static int doCheck(int count, String name, int page, String phrase) throws UnsupportedEncodingException, InterruptedException {
        String text = URLEncoder.encode(phrase, WordstatParse.ENC);
        String textGeo = URLEncoder.encode("", WordstatParse.ENC);
        String geoCode = URLEncoder.encode("", WordstatParse.ENC);
        String readyURL = WordstatParse.BASE_URL + "&page=" + page + "&t=" + text + "&geo=" + geoCode + "&text_geo=" + textGeo;
        try {
            Document doc = Jsoup.connect(readyURL).
                    header("user-agent", "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0").
                    header("Cookie", "yp=1628953306.sp.nd:50:ws:1:lang:!#1628139604.udn.c2hlbXBsaW5lcg==; yandexuid=36261312612900; fuid01=4d726ae12b1a1ac0.N9hJY3OOtWG-kEtar5NvfvMUs1Xo_8AUqbE-fG1uUYhwf2PZq1e_rMNyTIPcAliV5rOj5oRQaNMCW7Z2qn2HXaeA_Otjy40U2yeL3hFKkrbBAo6y88nb2eM2jOvZk-KQ; yabs-frequency=/3/hNO30ni9Pm000tUn01qR2Jm0005t0W0N60dS8t033HW9XPMj0mqO2Pm0/; my=YwECAAAnAgAALQECAA==; L=A39SC35HeVJlX05NeVpTUwMBAFh/bGdcNhoKMCoZYjE8UyAONRw9GgkaWCIdAnAeARQAOz8SMRpjBHdCJjNgWw==.1312779604.9074.268430.03ebff42cc506f579abb06a175673d47; spravka=dD0xMzEyNjQ5MjM4O2k9MTA5LjIwNS4yNTMuMTM1O3U9MTMxMjY0OTIzODkzNzY5MTU3MTtoPTY0M2FlZGZjYzkyZWQ2Mjk3OTIxOTUyYzhiYjk1Mjk2; t=p; yandex_login=shempliner; yandex_mail=shempliner; ys=udn.c2hlbXBsaW5lcg==; Session_id=1312779604.645.0.118550753.2:330838428:230.8:1312779604611:1388338972:13.77466.36850.267a73e88a26321cca687cc4f888684e").
                    timeout(WordstatParse.TIMEOUT).
                    get();
//                System.out.println(doc);
            String element = doc.select("table.campaign tr").get(1).siblingElements().get(1).text();
            int firstIndex = element.indexOf(new String(new char[]{8212})) + 2;
            int lastIndex = element.indexOf("показ") - 1;
            element = element.substring(firstIndex, lastIndex);
            int shows = Integer.parseInt(element);
//            if (shows > LIMIT) {
//                System.out.println(name);
//            }
            System.out.println(count + ". " + shows + "\t" + name + "\t\t" + phrase);
            Thread.sleep(5000);
        } catch (IOException e) {
            Thread.sleep(WordstatParse.DELAY_PHRASE);
            System.out.println(e.getMessage() + " Reconnect..");
        }
        return count;
    }
}
